package com.android.hidephotosplus;

import java.io.File;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.util.Log;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.android.hidephotosplus.util.Config;
import com.android.hidephotosplus.util.Util;
import com.android.hidephotosplus.view.MListPreference;

public class AppSettings extends SherlockPreferenceActivity implements
		OnPreferenceChangeListener {

	private MListPreference listPrefStorage;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.settings);
		listPrefStorage = (MListPreference) findPreference(Config.KEY_STORAGE);
		listPrefStorage.setOnPreferenceChangeListener(this);
	}

	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		if (Config.KEY_STORAGE.equals(preference.getKey())) {
			int value = Integer.parseInt(newValue.toString());
			boolean b = true;
			if (value == Config.TYPE_STORAGE_EXTERNAL) {
				File file = new File(Config.PATH_EXTERNAL);
				b = file.exists();
				if (!b) {
					Toast.makeText(getApplicationContext(),
							getString(R.string.not_found_sdcard),
							Toast.LENGTH_SHORT).show();
					listPrefStorage.setValue(String
							.valueOf(Config.TYPE_STORAGE_INTERNAL));
				}
			}
			if (b) {
				String path = Config.getPathFinal(value);
				if (path != null) {
					File dir = new File(path);
					if (!dir.exists())
						dir.mkdirs();
				}
				listPrefStorage.setValue(newValue.toString());
				showDialogChangeStorage(value);
			}
		}
		return false;
	}

	private void showDialogChangeStorage(final int value) {
		AlertDialog.Builder builder = new Builder(this);
		String from = null;
		if (value == Config.TYPE_STORAGE_INTERNAL)
			from = getString(R.string.sdcard);
		else
			from = getString(R.string.internal);
		builder.setTitle(getString(R.string.do_you_want));
		builder.setMessage(String.format(
				getString(R.string.move_hidden_media_from), from)
				+ " "
				+ listPrefStorage.getEntry().toString());

		builder.setPositiveButton(getString(R.string.ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						new Util.MoveMedia(AppSettings.this, value).execute();

					}
				});
		builder.setNegativeButton(getString(R.string.cancel),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				});
		builder.show();
	}

}
